package com.ctshk.rpc.order.tour.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.enums.NumberConstant;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.utils.CharUtil;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.order.tour.entity.SeriesOrderInsurance;
import com.ctshk.rpc.order.tour.entity.SeriesOrderReceiptInsurance;
import com.ctshk.rpc.order.tour.mapper.SeriesOrderInsuranceMapper;
import com.ctshk.rpc.order.tour.mapper.SeriesOrderReceiptInsuranceMapper;
import com.ctshk.rpc.order.tour.req.custom.ReceiptInsuranceAddReq;
import com.ctshk.rpc.order.tour.service.ISeriesOrderInsuranceService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.tour.dto.schedule.SeriesTripScheduleDTO;
import com.ctshk.rpc.tour.service.ISeriesTripScheduleService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Objects;

/**
 * <p>
 * 保险购买记录 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-05-22
 */
@DubboService
public class SeriesOrderInsuranceServiceImpl extends ServiceImpl<SeriesOrderInsuranceMapper, SeriesOrderInsurance> implements ISeriesOrderInsuranceService {

    @Autowired
    private SeriesOrderReceiptInsuranceMapper orderReceiptInsuranceMapper;
    @Autowired
    private SeriesOrderInsuranceMapper orderInsuranceMapper;

    @DubboReference
    private ISysUserService sysUserService;
    @DubboReference
    private ISeriesTripScheduleService tripScheduleService;


    /**
     * 生成保单收据
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createInsuranceReceipt(ReceiptInsuranceAddReq req) {
        if(req.getReceiptInsuranceId() != null){
            //修改操作
            SeriesOrderReceiptInsurance orderReceiptInsurance = orderReceiptInsuranceMapper.selectById(req.getReceiptInsuranceId());
            if (orderReceiptInsurance == null || Objects.equals(orderReceiptInsurance.getIsDeleted(), NumberConstant.ONE.getValue())){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4023);
            }
            orderReceiptInsurance.setTouristName(req.getTouristName());
            orderReceiptInsurance.setModifiedId(req.getUserId());
            int update = orderReceiptInsuranceMapper.updateById(orderReceiptInsurance);
            if (update <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
            return orderReceiptInsurance.getId();
        }
        //查询保单
        SeriesOrderInsurance insurance = orderInsuranceMapper.selectById(req.getInsuranceId());
        if (insurance == null || Objects.equals(insurance.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4023);
        }
        //查询是否已有收据
        QueryWrapper<SeriesOrderReceiptInsurance> receiptInsuranceQueryWrapper = new QueryWrapper<>();
        receiptInsuranceQueryWrapper.eq("insurance_id",req.getInsuranceId());
        receiptInsuranceQueryWrapper.eq("is_deleted",0);
        SeriesOrderReceiptInsurance receiptInsurance = orderReceiptInsuranceMapper.selectById(req.getInsuranceId());
        if (receiptInsurance != null){
            return receiptInsurance.getId();
        }
        //新增保单收据
        receiptInsurance = EntityUtil.copy(req,SeriesOrderReceiptInsurance.class);
        receiptInsurance.setId(SnowflakeIdWorker.nextId());
        receiptInsurance.setOrderId(insurance.getOrderId());
        receiptInsurance.setScheduleId(insurance.getScheduleId());
        receiptInsurance.setInsuranceNumber(insurance.getInsuranceNumber());
        receiptInsurance.setName(insurance.getName());
        receiptInsurance.setTouristName(insurance.getPolicyHolderName());
        try {
            UserDTO userDTO = sysUserService.queryCacheUser(req.getUserId());
            if (userDTO != null){
                receiptInsurance.setDeptCode(userDTO.getDeptCode());
            }
        }catch (Exception e){
            throw new BusinessException(SystemError.SYS_417);
        }
        SeriesTripScheduleDTO tripSchedule = tripScheduleService.getTripScheduleId(insurance.getScheduleId());
        receiptInsurance.setTripNumber(tripSchedule.getTripNumber());
        if (tripSchedule.getDepartureDate() != null && tripSchedule.getSeriesTripScheduleTeamRuleDTO().getDeliveryDays() != null){
            LocalDate deliveryDate = tripSchedule.getDepartureDate().plusDays(tripSchedule.getSeriesTripScheduleTeamRuleDTO().getDeliveryDays().longValue());
            receiptInsurance.setDeliveryDate(deliveryDate);
        }
        receiptInsurance.setDays(insurance.getDays());
        if (tripSchedule.getDepartureDate() != null){
            StringBuffer departDate = new StringBuffer(DateUtil.fmtLocalDate(tripSchedule.getDepartureDate(), "yyyy-MM-dd"));
            departDate.append("("+ CharUtil.getWeekDay(tripSchedule.getDepartureDate().getDayOfWeek().getValue())+")");
            receiptInsurance.setDepartDate(departDate.toString());
        }
        receiptInsurance.setTotalAmount(insurance.getTotalAmount());
        StringBuffer itinerary = new StringBuffer("("+tripSchedule.getSeriesTripScheduleDataDTO().getGroupTypeName()+")");
        itinerary.append(tripSchedule.getSeriesTripScheduleDataDTO().getTitle());
        receiptInsurance.setBank(req.getPayMethod());
        receiptInsurance.setItinerary(itinerary.toString());
        /*receiptInsurance.setTourFeeInclude(tripSchedule.getTourFeeInclude());
        receiptInsurance.setTourFeeExclude(receiptInsurance.getTourFeeExclude());
        receiptInsurance.setSignNotice(tripSchedule.getSignNotice());
        receiptInsurance.setRemark(tripSchedule.getRemark());*/
        receiptInsurance.setCreateDate(insurance.getGmtCreate().toLocalDate());
        receiptInsurance.setCreateId(req.getUserId());
        receiptInsurance.setIsDeleted(0);
        int insert = orderReceiptInsuranceMapper.insert(receiptInsurance);
        //更新保单状态
        insurance.setIsPrint(1);
        insurance.setModifiedId(req.getUserId());
        int update = orderInsuranceMapper.updateById(insurance);
        if (insert <= 0 || update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return receiptInsurance.getId();
    }
}
